package org.ru.mse10.cvis.web.bean;

import java.util.HashSet;
import java.util.Set;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.ru.mse10.cvis.service.EntityService;

/**
 * The Class BaseFormBean.
 * 
 * @param <E>
 *            the element type
 * @param <S>
 *            the generic type
 */
@SessionScoped
@ManagedBean(name = "baseFormBean")
public class BaseFormBean<E, S extends EntityService> extends BaseUIBean {

	/** The permissions. */
	private Set<Integer> permissions = new HashSet<Integer>();

	/** The target entity. */
	private E targetEntity;

	/** The readonly. */
	private boolean readonly = true;

	/**
	 * Action save.
	 */
	public void actionSave() {
		setTargetEntity(getService().save(getTargetEntity()));
		setReadonly(true);
	}

	/**
	 * Action edit.
	 */
	public void actionEdit() {
		setReadonly(false);
	}

	/**
	 * Action cancel edit.
	 * 
	 * @return the string
	 */
	public String actionCancelEdit() {
		setReadonly(true);
		return null;
	}

	/**
	 * Gets the service.
	 * 
	 * @return the service
	 */
	protected S getService() {
		return null;
	}

	/**
	 * Checks if is readonly.
	 * 
	 * @return the readonly
	 */
	public boolean isReadonly() {
		return readonly;
	}

	/**
	 * Sets the readonly.
	 * 
	 * @param readonly
	 *            the readonly to set
	 */
	public void setReadonly(boolean readonly) {
		this.readonly = readonly;
	}

	/**
	 * Gets the target entity.
	 * 
	 * @return the targetEntity
	 */
	public E getTargetEntity() {
		return targetEntity;
	}

	/**
	 * Sets the target entity.
	 * 
	 * @param targetEntity
	 *            the targetEntity to set
	 */
	public void setTargetEntity(E targetEntity) {
		this.targetEntity = targetEntity;
	}

	/**
	 * Gets the user.
	 * 
	 * @param <User>
	 *            the generic type
	 * @return the user
	 */
	@SuppressWarnings("unchecked")
	public <User> User getUser() {
		return (User) FacesContext.getCurrentInstance().getExternalContext()
				.getSessionMap().get("user");
	}

	/**
	 * Sets the user.
	 * 
	 * @param <User>
	 *            the generic type
	 * @param user
	 *            the new user
	 */
	public <User> void setUser(User user) {
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap()
				.put("user", user);
		permissions.clear();
		// for (Privilege privilege : user.get) {
		// initialize privileges list here!!! TODO:
		// }

	}

}
